﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2020-12-04 15:20
    /// 描 述：项目管理
    /// </summary>
    public class ec_projectService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取项目选择页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public IEnumerable<ec_projectEntity> GetProjectSelectPageList(Pagination pagination, string queryJson)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT t1.*
                                    ,t2.F_ItemName AS ShipTypeCNName
                                    ,t3.F_ItemName AS ShipTypeENName
                                    ,t4.F_ItemName AS ShipSocietyName
                                    ,t5.F_ItemName AS FlagStateName
                                    ,t6.F_RealName CreateUserName
                                FROM ec_project t1
                                LEFT JOIN lr_base_dataitemdetail t2 ON t2.F_ItemValue = t1.ShipTypeCN AND t2.F_ItemId IN (SELECT st1.F_ItemId FROM LR_Base_DataItem st1 WHERE st1.F_ItemCode= 'Be_ShipTypeCN') 
                                LEFT JOIN lr_base_dataitemdetail t3 ON t3.F_ItemValue = t1.ShipTypeEN AND t3.F_ItemId IN (SELECT st1.F_ItemId FROM LR_Base_DataItem st1 WHERE st1.F_ItemCode= 'Be_ShipTypeEN') 
                                LEFT JOIN lr_base_dataitemdetail t4 ON t4.F_ItemValue = t1.ShipSociety AND t4.F_ItemId IN (SELECT st1.F_ItemId FROM LR_Base_DataItem st1 WHERE st1.F_ItemCode= 'Be_ShipSociety') 
                                LEFT JOIN lr_base_dataitemdetail t5 ON t5.F_ItemValue = t1.FlagState AND t5.F_ItemId IN (SELECT st1.F_ItemId FROM LR_Base_DataItem st1 WHERE st1.F_ItemCode= 'Be_FlagState') 
                                LEFT JOIN lr_base_user t6 ON t1.CreateUserID = t6.F_UserId
                                WHERE 1=1 ");
                var queryParam = queryJson.ToJObject();

                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["ProjectName"].IsEmpty())
                {
                    dp.Add(new SugarParameter("ProjectName", "%" + queryParam["ProjectName"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t1.ProjectName LIKE @ProjectName ");
                }
                UserInfo userInfo = LoginUserInfo.Get();
                if (userInfo != null && !userInfo.isSystem)
                {
                    dp.Add(new SugarParameter("UserID", userInfo.userId, DbType.String));
                    strSql.Append(" AND t1.ProjectId in (SELECT ProjectId from lr_base_userrelation WHERE F_UserId = @UserID AND F_Category = 1 ) ");
                }
                if (!queryParam["NotProjectId"].IsEmpty())
                {
                    dp.Add(new SugarParameter("NotProjectId", queryParam["NotProjectId"].ToString(), DbType.String));
                    strSql.Append(" AND t1.ProjectId <> @NotProjectId ");
                }
                //return this.BaseRepository("BaseDb").FindList<ec_projectEntity>(strSql.ToString(), dp, pagination);
                int total = 0;
                var list = SqlSugarHelper.Db.SqlQueryable<ec_projectEntity>(strSql.ToString()).AddParameters(dp).ToPageList(pagination.page, pagination.rows, ref total);
                pagination.records = total;
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_projectEntity GetEntity(string keyValue)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT
                                    t1.*
                                FROM ec_project t1 
                                WHERE t1.ProjectId=@ProjectId
                                ");
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                dp.Add(new SugarParameter("ProjectId", keyValue));
                return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_projectEntity>(strSql.ToString(), dp);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, List<string> listTableCode, int projectIndex)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                //删除项目时，需要删除项目对应的业务数据表
                if (listTableCode != null && listTableCode.Count > 0)
                {
                    string sqlStatement = "";
                    foreach (var item in listTableCode)
                    {
                        sqlStatement += $" DROP TABLE IF EXISTS `{item}_{projectIndex}`;";
                    }
                    SqlSugarHelper.Db.Ado.ExecuteCommand(sqlStatement);
                }
                _projectRepository.Delete(t => t.ProjectId == keyValue);
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_projectEntity entity)
        {
            try
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    _projectRepository.Update(entity);
                }
                else
                {
                    entity.Create();
                    _projectRepository.Insert(entity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 执行sql语句
        /// <param name="projectIndex">项目序号</param>
        /// <param name="listTableName">要复制的表名集合</param>
        /// <param name="isCopyData">是否要复制数据,默认为不复制</param>
        /// <param name="CopyTableData">新建项目时需要复制“是否复制数据”为1的表数据</param>
        /// <summary>
        /// <returns></returns>
        public void ExecuteSQL(List<string> listTableName, int projectIndex, bool isCopyData, List<string> CopyTableData)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if(listTableName!=null && listTableName.Count > 0)
                {
                    string sqlStatement = "";
                    foreach (var item in listTableName)
                    {
                        if (isCopyData)
                        {
                            sqlStatement += $@" DROP TABLE IF EXISTS `{item}_{projectIndex}`;
                                      CREATE TABLE {item}_{projectIndex} SELECT * FROM {item};";
                        }
                        else
                        {
                            if (CopyTableData.Contains(item))
                            {
                                sqlStatement += $@" DROP TABLE IF EXISTS `{item}_{projectIndex}`;
                                      CREATE TABLE {item}_{projectIndex} SELECT * FROM {item};";
                            }
                            else
                            {
                                sqlStatement += $@" DROP TABLE IF EXISTS `{item}_{projectIndex}`;
                                      CREATE TABLE {item}_{projectIndex} (LIKE {item});";
                            }
                        }
                    }
                    SqlSugarHelper.Db.Ado.ExecuteCommand(sqlStatement);
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

    }
}
